/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package by.bsuir.bbs.dao;

import by.bsuir.bbs.dao.exceptions.IllegalOrphanException;
import by.bsuir.bbs.dao.exceptions.NonexistentEntityException;
import by.bsuir.bbs.dao.exceptions.PreexistingEntityException;
import by.bsuir.bbs.dao.exceptions.RollbackFailureException;
import by.bsuir.bbs.persistence.Ad;
import by.bsuir.bbs.persistence.AdPK;
import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import by.bsuir.bbs.persistence.User;
import by.bsuir.bbs.persistence.Comment;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.transaction.UserTransaction;

/**
 *
 * @author Администратор
 */
public class AdJpaController implements Serializable {

    public AdJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Ad ad) throws PreexistingEntityException, RollbackFailureException, Exception {
        if (ad.getAdPK() == null) {
            ad.setAdPK(new AdPK());
        }
        if (ad.getCommentCollection() == null) {
            ad.setCommentCollection(new ArrayList<Comment>());
        }
        ad.getAdPK().setUserIduser(ad.getUser().getUserId());
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            User user = ad.getUser();
            if (user != null) {
                user = em.getReference(user.getClass(), user.getUserId());
                ad.setUser(user);
            }
            Collection<Comment> attachedCommentCollection = new ArrayList<Comment>();
            for (Comment commentCollectionCommentToAttach : ad.getCommentCollection()) {
                commentCollectionCommentToAttach = em.getReference(commentCollectionCommentToAttach.getClass(), commentCollectionCommentToAttach.getCommentPK());
                attachedCommentCollection.add(commentCollectionCommentToAttach);
            }
            ad.setCommentCollection(attachedCommentCollection);
            em.persist(ad);
            if (user != null) {
                user.getAdCollection().add(ad);
                user = em.merge(user);
            }
            for (Comment commentCollectionComment : ad.getCommentCollection()) {
                Ad oldAdOfCommentCollectionComment = commentCollectionComment.getAd();
                commentCollectionComment.setAd(ad);
                commentCollectionComment = em.merge(commentCollectionComment);
                if (oldAdOfCommentCollectionComment != null) {
                    oldAdOfCommentCollectionComment.getCommentCollection().remove(commentCollectionComment);
                    oldAdOfCommentCollectionComment = em.merge(oldAdOfCommentCollectionComment);
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            if (findAd(ad.getAdPK()) != null) {
                throw new PreexistingEntityException("Ad " + ad + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Ad ad) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        ad.getAdPK().setUserIduser(ad.getUser().getUserId());
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Ad persistentAd = em.find(Ad.class, ad.getAdPK());
            User userOld = persistentAd.getUser();
            User userNew = ad.getUser();
            Collection<Comment> commentCollectionOld = persistentAd.getCommentCollection();
            Collection<Comment> commentCollectionNew = ad.getCommentCollection();
            List<String> illegalOrphanMessages = null;
            for (Comment commentCollectionOldComment : commentCollectionOld) {
                if (!commentCollectionNew.contains(commentCollectionOldComment)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Comment " + commentCollectionOldComment + " since its ad field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            if (userNew != null) {
                userNew = em.getReference(userNew.getClass(), userNew.getUserId());
                ad.setUser(userNew);
            }
            Collection<Comment> attachedCommentCollectionNew = new ArrayList<Comment>();
            for (Comment commentCollectionNewCommentToAttach : commentCollectionNew) {
                commentCollectionNewCommentToAttach = em.getReference(commentCollectionNewCommentToAttach.getClass(), commentCollectionNewCommentToAttach.getCommentPK());
                attachedCommentCollectionNew.add(commentCollectionNewCommentToAttach);
            }
            commentCollectionNew = attachedCommentCollectionNew;
            ad.setCommentCollection(commentCollectionNew);
            ad = em.merge(ad);
            if (userOld != null && !userOld.equals(userNew)) {
                userOld.getAdCollection().remove(ad);
                userOld = em.merge(userOld);
            }
            if (userNew != null && !userNew.equals(userOld)) {
                userNew.getAdCollection().add(ad);
                userNew = em.merge(userNew);
            }
            for (Comment commentCollectionNewComment : commentCollectionNew) {
                if (!commentCollectionOld.contains(commentCollectionNewComment)) {
                    Ad oldAdOfCommentCollectionNewComment = commentCollectionNewComment.getAd();
                    commentCollectionNewComment.setAd(ad);
                    commentCollectionNewComment = em.merge(commentCollectionNewComment);
                    if (oldAdOfCommentCollectionNewComment != null && !oldAdOfCommentCollectionNewComment.equals(ad)) {
                        oldAdOfCommentCollectionNewComment.getCommentCollection().remove(commentCollectionNewComment);
                        oldAdOfCommentCollectionNewComment = em.merge(oldAdOfCommentCollectionNewComment);
                    }
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                AdPK id = ad.getAdPK();
                if (findAd(id) == null) {
                    throw new NonexistentEntityException("The ad with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(AdPK id) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Ad ad;
            try {
                ad = em.getReference(Ad.class, id);
                ad.getAdPK();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The ad with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            Collection<Comment> commentCollectionOrphanCheck = ad.getCommentCollection();
            for (Comment commentCollectionOrphanCheckComment : commentCollectionOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Ad (" + ad + ") cannot be destroyed since the Comment " + commentCollectionOrphanCheckComment + " in its commentCollection field has a non-nullable ad field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            User user = ad.getUser();
            if (user != null) {
                user.getAdCollection().remove(ad);
                user = em.merge(user);
            }
            em.remove(ad);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Ad> findAdEntities() {
        return findAdEntities(true, -1, -1);
    }

    public List<Ad> findAdEntities(int maxResults, int firstResult) {
        return findAdEntities(false, maxResults, firstResult);
    }

    private List<Ad> findAdEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Ad.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Ad findAd(AdPK id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Ad.class, id);
        } finally {
            em.close();
        }
    }

    public int getAdCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Ad> rt = cq.from(Ad.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
